﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace Achievement.Common
{
    public static class CovertHelper
    {
        
        private static int StringToInteger(this string s)
        {
            int num; 
            int.TryParse(s, out num);
            string aa = "";
            return num;
        }

        private static decimal StringToDecimal(this string s)
        {
            decimal num;
            decimal.TryParse(s, out num);
            return num;
        }

        private static double StringToDouble(this string s)
        {
            double num;
            double.TryParse(s, out num);
            return num;
        }

        private static long StringToLong(this string s)
        {
            long num;
            long.TryParse(s, out num);
            return num;
        }

        private static short StringToShortInt(this string s)
        {
            short num;
            short.TryParse(s, out num);
            return num;
        }

        /// <summary>
        /// 安全转换布尔类型
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool SecureToBoolean(this object obj)
        {
            if ((obj == DBNull.Value) || (obj == null))
            {
                return false;
            }
            if (!(obj.SecureToString().ToLower() == "true"))
            {
                return false;
            }
            return true;
        }

        
        /// <summary>
        /// 安全转换时间类型
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static DateTime SecureToDateTime(this object obj)
        {
            DateTime time;
            DateTime.TryParse(obj.SecureToString(), out time);
            return time;
        }

        /// <summary>
        /// 安全转换自定义时间类型
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="sFormat"></param>
        /// <returns></returns>
        public static string SecureToDateTime(this object obj, string sFormat)
        {
            return obj.SecureToDateTime().ToString(sFormat);
        }


        /// <summary>
        /// 安全转换短时间类型
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string SecureToShortDateTime(object obj)
        {
            return obj.SecureToDateTime("yyyy-MM-dd");
        }

        /// <summary>
        /// 安全转换十进制类型
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static decimal SecureToDecimal(this object obj)
        {
            return obj.SecureToString().StringToDecimal();
        }

        /// <summary>
        /// 安全转换双精度浮点类型
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static double SecureToDouble(this object obj)
        {
            return obj.SecureToString().StringToDouble();
        }

        /// <summary>
        /// 安全转换字符类型
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string SecureToString(this object obj)
        {
            if ((obj != DBNull.Value) && (obj != null))
            {
                return obj.ToString();
            }
            return string.Empty;
        }

        /// <summary>
        /// 安全转换32位符号整数类型
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static int SecureToInt32(this object obj)
        {
            return obj.SecureToString().StringToInteger();
        }

        /// <summary>
        /// 安全转换16位符号整数类型
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static short GetShortInt(object obj)
        {
            return obj.SecureToString().StringToShortInt();
        }

        /// <summary>
        /// 安全转换64位符号整数类型
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static long SecureToLong(this object obj)
        {
            return obj.SecureToString().StringToLong();
        }

        /// <summary>
        /// 表达式转换字典型，如：new {key="a",value="b" }
        /// </summary>
        /// <typeparam name="K"></typeparam>
        /// <typeparam name="V"></typeparam>
        /// <param name="values"></param>
        /// <returns></returns>
        public static Dictionary<K, V> SecureToDictionary<K, V>(this object values)
        {
            Dictionary<K, V> arrary = new Dictionary<K, V>();
            if (values != null)
            {
                foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(values))
                {
                    object obj2 = descriptor.GetValue(values);
                    arrary.Add(descriptor.Name.ConvertType<K>(), obj2.ConvertType<V>());
                }
            }
            return arrary;
        }

        public static T ConvertType<T>(this object value)
        {
            if (typeof(T) == typeof(String))
            {
                value = value.ToString();
            }
            if (typeof(T) == typeof(Int32))
            {
                value = value.SecureToInt32();
            }
            return (T)value;
        }

        /// <summary>
        /// 生成Json格式
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ObjectToJson(this object obj)
        {
            return obj.ObjectToJson<object>();
        }

        /// <summary>
        /// 生成Json格式
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ObjectToJson<T>(this T obj)
        {
            if (obj != null)
            {
                DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType());
                using (MemoryStream stream = new MemoryStream())
                {
                    json.WriteObject(stream, obj);
                    string szJson = Encoding.UTF8.GetString(stream.ToArray());
                    return szJson;
                }
            }
            return string.Empty;
        }

        /// <summary>
        /// 获取Json的Model
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="szJson"></param>
        /// <returns></returns>
        public static T JsonToObject<T>(this string szJson)
        {
            if (!string.IsNullOrEmpty(szJson))
            {
                T obj = Activator.CreateInstance<T>();
                using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
                {
                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                    return (T)serializer.ReadObject(ms);
                }
            }
            return default(T);
        }

        /// <summary>
        /// 把对象序列化为XML字符串
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="obj">对象</param>
        /// <returns></returns>
        public static string SerializationXml<T>(this T obj)
        {
            StringBuilder content = new StringBuilder();
            StringWriter writer = new StringWriter(content);
            XmlTextWriter xmlWriter = new XmlTextWriter(writer);
            XmlSerializer xs = new XmlSerializer(typeof(T));
            xs.Serialize(xmlWriter, obj);
            return content.ToString();
        }

        public static void SerializationXml<T>(this T obj,string path)
        {
            Stream file = new FileStream(path, FileMode.Create, FileAccess.Write); 
            XmlSerializer xs = new XmlSerializer(typeof(T));
            xs.Serialize(file, obj);
        }

        public static T DeserializeXml<T>(this string xml)
        {
            StringReader sr = new StringReader(xml);
            XmlSerializer xs = new XmlSerializer(typeof(T));
            return (T)xs.Deserialize(sr);
        }

        public static string SecureSubString(this string str, int count)
        {
            if (str.Length < count)
            {
                count = str.Length;
            }
            return str.Substring(0, count);
        }

        public static string SecureSubString(this string str, int count,string addStr)
        {
            if (str.Length < count)
            {
                count = str.Length;
                addStr = string.Empty;
            }
            return str.Substring(0, count) + addStr;
        }
    }
}
